<template>
  <div class="role-management">
    <!-- 主要内容区域 - 添加水平和垂直滚动容器，包裹整个页面内容 -->
    <div class="main-content-wrapper">
    <el-card>
      <!-- 移除卡片头部标题 -->
      
      <!-- 搜索区域 -->
      <el-form :model="searchForm" class="search-form" label-width="80px">
        <el-row :gutter="20" align="middle">
          <el-col :span="6">
            <el-form-item label="角色名称" inline>
              <el-input v-model="searchForm.name" placeholder="请输入" style="width: 180px;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="角色标识" inline>
              <el-input v-model="searchForm.label" placeholder="请输入" style="width: 180px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="text-align: right;">
            <el-form-item>
              <el-button type="primary" @click="handleSearch" style="margin-right: 10px;">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      
      <!-- 操作按钮 - 置于左边 -->
      <div class="action-buttons-left" style="margin-bottom: 20px;">
        <el-button type="primary" @click="handleAdd">添加角色</el-button>
      </div>
      
      <!-- 表格数据 -->
      <el-table 
        :data="roleList" 
        stripe 
        style="width: 100%; min-width: 1320px; font-size: 14px;"
        :header-cell-style="{ 'font-size': '14px', 'padding': '10px 12px' }"
      >
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column prop="name" label="角色名称" width="180" />
        <el-table-column prop="label" label="角色标识" width="180" />
        <el-table-column prop="remark" label="备注" width="200" />
        <el-table-column prop="updateTime" label="最后修改时间" width="240" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <div style="display: flex; gap: 10px; justify-content: center;">
              <el-button type="primary" size="small" @click="handleEdit(row)">修改</el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="350px"
      @close="handleClose"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="label">
          <el-input v-model="formData.label" placeholder="请输入角色标识" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 表格数据
const roleList = ref([])

// 搜索表单
const searchForm = reactive({
  name: '',
  label: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formData = reactive({
  id: '',
  name: '',
  label: '',
  remark: ''
})

// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 1, max: 10, message: '角色名称长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  label: [
    { required: true, message: '请输入角色标识', trigger: 'blur' },
    { min: 1, max: 20, message: '角色标识长度在 1 到 20 个字符', trigger: 'blur' }
  ],
  remark: [
    { max: 50, message: '备注长度不能超过 50 个字符', trigger: 'blur' }
  ]
})

const formRef = ref()

// 获取角色列表
const getRoleList = async () => {
  try {
    const params = {
      ...searchForm,
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    const response = await axios.get('/api/roles', {
      params: params
    })
    
    const result = response.data
    
    if (result && typeof result === 'object') {
      if (result.code === 1) {
        if (result.data && Array.isArray(result.data.rows)) {
          roleList.value = result.data.rows
          pagination.total = Number(result.data.total) || 0
        } else {
          ElMessage.error('响应数据格式错误')
        }
      } else {
        ElMessage.error(result.msg || '获取角色列表失败')
      }
    } else {
      ElMessage.error('获取角色列表失败')
    }
  } catch (error) {
    ElMessage.error('获取角色列表失败')
    console.error('获取角色列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getRoleList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.label = ''
  pagination.currentPage = 1
  getRoleList()
}

// 重置表单数据
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  formData.id = ''
  formData.name = ''
  formData.label = ''
  formData.remark = ''
}

// 添加角色
const handleAdd = () => {
  dialogTitle.value = '添加角色'
  resetForm()
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = async (row) => {
  try {
    const response = await axios.get(`/api/roles/${row.id}`)
    const result = response.data
    
    if (result.code === 1) {
      dialogTitle.value = '编辑角色'
      formData.id = result.data.id
      formData.name = result.data.name
      formData.label = result.data.label
      formData.remark = result.data.remark
      dialogVisible.value = true
    } else {
      ElMessage.error(result.msg || '获取角色信息失败')
    }
  } catch (error) {
    ElMessage.error('获取角色信息失败')
    console.error('获取角色信息失败:', error)
  }
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除角色「${row.name}」吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await axios.delete(`/api/roles/${row.id}`)
      const result = response.data
      
      if (result.code === 1) {
        ElMessage.success('删除成功')
        getRoleList()
      } else {
        ElMessage.error(result.msg || '删除失败')
      }
    } catch (error) {
      ElMessage.error('删除失败')
      console.error('删除角色失败:', error)
    }
  }).catch(() => {
    // 取消删除
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const requestData = {
      name: formData.name,
      label: formData.label,
      remark: formData.remark
    }
    
    let response
    if (formData.id) {
      // 修改角色
      response = await axios.put('/api/roles', {
        ...requestData,
        id: formData.id
      })
    } else {
      // 添加角色
      response = await axios.post('/api/roles', requestData)
    }
    
    const result = response.data
    if (result.code === 1) {
      ElMessage.success(formData.id ? '修改成功' : '添加成功')
      dialogVisible.value = false
      getRoleList()
    } else {
      ElMessage.error(result.msg || (formData.id ? '修改失败' : '添加失败'))
    }
  } catch (error) {
    if (error.name === 'Error') {
      ElMessage.error('操作失败')
      console.error('提交表单失败:', error)
    }
    // 表单验证失败时，element-plus 会自动提示
  }
}

// 关闭对话框
const handleClose = () => {
  resetForm()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  getRoleList()
}

// 当前页码改变
const handleCurrentChange = (current) => {
  pagination.currentPage = current
  getRoleList()
}

// 页面挂载时获取数据
onMounted(() => {
  getRoleList()
})
</script>

<style scoped>
.role-management {
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.main-content-wrapper {
  overflow: auto; /* 同时启用水平和垂直滚动 */
  max-height: calc(100vh - 100px); /* 根据页面高度动态调整，确保足够空间 */
  position: relative;
  min-height: 600px;
  padding: 0 15px;
}

/* 自定义滚动条样式 */
.main-content-wrapper::-webkit-scrollbar {
  height: 10px; /* 水平滚动条高度 */
  width: 10px;  /* 垂直滚动条宽度 */
}

.main-content-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 5px;
}

.main-content-wrapper::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 5px;
}

.main-content-wrapper::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 确保表格内容在滚动时不会溢出 */
:deep(.el-table) {
  min-width: 100%;
  width: auto;
  margin-bottom: 0;
}

/* 调整操作按钮样式 */
:deep(.el-button--small) {
  padding: 4px 12px;
  font-size: 12px;
}

/* 表格样式优化 */
:deep(.el-table__row) {
  height: 45px;
}

/* 调整列间距 */
:deep(.el-table__cell) {
  padding: 20px 25px;
  min-width: fit-content;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

/* 主内容滚动容器 - 服务于整个页面内容 */
.main-content-wrapper {
  overflow-x: auto; /* 优先启用水平滚动 */
  overflow-y: auto; /* 同时启用垂直滚动 */
  max-height: calc(100vh - 100px); /* 根据页面高度动态调整，确保足够空间 */
  position: relative;
  min-height: 600px;
  padding: 0 15px;
  white-space: nowrap; /* 防止内容换行 */
}

/* 确保卡片元素在滚动容器中正确显示 */
.main-content-wrapper > .el-card {
  min-width: 1320px; /* 最小宽度，确保表格内容不被压缩 */
  width: 100%;
  box-sizing: border-box;
  white-space: normal; /* 允许卡片内部内容正常换行 */
}

/* 自定义滚动条样式 */
.main-content-wrapper::-webkit-scrollbar {
  height: 10px; /* 水平滚动条高度 */
  width: 10px;  /* 垂直滚动条宽度 */
}

.main-content-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 5px;
}

.main-content-wrapper::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 5px;
}

.main-content-wrapper::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 确保表格内容在滚动时不会溢出 */
:deep(.el-table) {
  min-width: 1320px; /* 确保表格有足够的最小宽度 */
  width: 100%;
  margin-bottom: 0;
}

/* 调整操作按钮样式 */
:deep(.el-button--small) {
  padding: 4px 12px;
  font-size: 12px;
}
</style>
